<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../tags/tag-item.html">
<dom-module id="mist-tags-field">
    <template>
        <style include="shared-styles dialogs">
        :host {
            padding: 0;
            margin: 0;
        }

        .tag-list {
            padding: 0 0 24px 0;
        }

        :host .tag-list>p {
            margin: 24px 0 0 0;
        }

        .submit-btn.add {
            margin: 0;
            padding: 0;
        }

        iron-icon {
            color: inherit !important;
        }

        paper-button.keyboard-focus {
            font-weight: bold !important;
        }

        .title {
            text-transform: capitalize;
            font-weight: bold;
        }
        </style>
        <div class="title">[[field.label]]</div>
        <div class="tag-list">
            <template is="dom-repeat" items="[[tags]]" as="tag">
                <tag-item tag="[[tag]]" index=[[index]]></tag-item>
            </template>
        </div>
        <paper-button class="submit-btn add" on-tap="_addTag">
            <iron-icon icon="add"></iron-icon> Add Tag
        </paper-button>
    </template>
    <script>
        Polymer({
            is: 'mist-tags-field',

            properties: {
                field: {
                    type: Object,
                    notify: true
                },
                tags: {
                    type: Array,
                    value: []
                }
            },
            observers: [
                '_tagsChanged(tags.*)'
            ],
            listeners: {
                'input': '_tagsChanged',
                'tag-delete': '_tagDeleteHandler'
            },
            ready: function() {

            },
            _addTag: function() {
                var newTag = {
                    key: '',
                    value: ''
                };
                this.push('tags', newTag);
            },
            _tagsChanged: function(tags) {
                var formattedTags = this.tags.filter(function(m){
                    return m.key.length;
                }).map(function(t){
                    console.log('t',t);
                    var tag = {};
                    tag[t.key] = t.value || null;
                    return tag;
                });
                this.set('field.value', formattedTags);
            },
            _tagDeleteHandler: function(e) {
                var tag = e.detail.tag,
                    index = this.tags.indexOf(tag);
                this.splice('tags', index, 1);
            },
        });
    </script>
</dom-module>